package com.bjpowernode.threadpool.monitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池运行情况监控
 *
 */
public class MonitorThreadPoolExecutor {

    private static final Logger logger = LoggerFactory.getLogger(MonitorThreadPoolExecutor.class);

    public static void main(String[] args) {
        ThreadPoolExecutor monitorThreadPoolExecutor = new ThreadPoolExecutor(
                8,
                16,
                15,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(1024),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        monitorThreadPoolExecutor.execute(() -> {
            // 统计线程池信息
            while (true) {
                System.out.println("----------------------------");

                int queueSize = monitorThreadPoolExecutor.getQueue().size();
                System.out.println("当前排队线程数：" + queueSize);

                int poolSize = monitorThreadPoolExecutor.getPoolSize();
                System.out.println("线程池的线程数量：" + poolSize);

                int activeCount = monitorThreadPoolExecutor.getActiveCount();
                System.out.println("当前活动线程数：" + activeCount);

                int largestPoolSize = monitorThreadPoolExecutor.getLargestPoolSize();
                System.out.println("线程池里曾经创建过的最大线程数量：" + largestPoolSize);

                long completedTaskCount = monitorThreadPoolExecutor.getCompletedTaskCount();
                System.out.println("执行完成线程数：" + completedTaskCount);

                long taskCount = monitorThreadPoolExecutor.getTaskCount();
                System.out.println("总线程数：" + taskCount);

                int corePoolSize = monitorThreadPoolExecutor.getCorePoolSize();
                System.out.println("线程池核心线程数：" + corePoolSize);

                int maximumPoolSize = monitorThreadPoolExecutor.getMaximumPoolSize();
                System.out.println("线程池最大线程数：" + maximumPoolSize);

                long keepAliveTime = monitorThreadPoolExecutor.getKeepAliveTime(TimeUnit.SECONDS);
                System.out.println("线程池线程空闲超时时间：" + keepAliveTime);

                try {
                    TimeUnit.MICROSECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        for (int i = 0; i < 1000; i++) {
            monitorThreadPoolExecutor.execute(() -> {
                System.out.println("线程-"+Thread.currentThread().getName() + "-正在执行......" + Thread.currentThread().getId());
            });
        }
    }
}